/**
 * Class CreditorAccountModule.
 * 
 * @author Maxime Ollagnier
 */
CreditorAccountModule.inherits(Module);
function CreditorAccountModule() {
	var that = this;
	
	this.creditor = undefined;
	this.accountTable = undefined;
	this.account = undefined;
	
	/** Account table */
	this.accountTable = new TableModule({
		'selectable' : true,
		'onSelect' : function(accountId) {
			that.editAccount(accountId);
		}
	});
	this.accountTable.id = 'accountTable';
	this.accountTable.columnList.push(new Column('name', I18n.get('name'), '38%', true));
	this.accountTable.columnList.push(new Column('bic', I18n.get('bic'), '16%', true));
	this.accountTable.columnList.push(new Column('iban', I18n.get('iban'), '30%', true));
	var activeColumn = new Column('active', I18n.get('active'), '8%');
	activeColumn.getAlt = undefined;
	activeColumn.getText = function(account) {
		var jQCheckbox = $('<input type="checkbox" ' + (account.active ? 'checked="checked"' : '') + ((UserManager.hasRoles(['WRITE_BIC_IBAN']) && (!Util.checkBoolTrue(account.byDefault) || !Util.checkBoolTrue(account.active))) ? '' : ' disabled="disabled"') + '></input>');
		jQCheckbox.change(function() {
			that.setActive(account, $(this).is(':checked'));
		});
		return jQCheckbox;
	};
	this.accountTable.columnList.push(activeColumn);
	var defaultColumn = new Column('default', I18n.get('default'), '8%');
	defaultColumn.clickable = false;
	defaultColumn.getAlt = undefined;
	defaultColumn.getText = function(account) {
		var jQCheckbox = $('<input type="checkbox" ' + (account.byDefault ? 'checked="checked"' : '') + ((UserManager.hasRoles(['WRITE_BIC_IBAN']) && (!Util.checkBoolTrue(account.byDefault) && Util.checkBoolTrue(account.active))) ? '' : ' disabled="disabled"') + '></input>');
		jQCheckbox.change(function() {
			that.setDefault(account);
		});
		return jQCheckbox;
	};
	this.accountTable.columnList.push(defaultColumn);
	
	/** Input Modules */
	this.inputName = new InputTextModule({
		'id' : 'inputName',
		'label' : I18n.get('name'),
		'placeholder' : I18n.get('name'),
		'mandatory' : true,
		'validationPattern' : ValidationPattern.VALID_DEFAULT,
		'validationMethod' : new ValidationMethod({
			'errorMessage' : I18n.get('creditor.account.name.exists'),
			'method' : function(value) {
				var unique = true;
				that.accountTable.objectMap.foreach(function(id, account) {
					unique = unique && (that.account.id == account.id || account.name != value);
				});
				return unique;
			}
		}),
		'onKeyUp' : function() { that.setJQFormTitle(); },
		'onEnter' : function() { that.saveAccount(); }
	});
	this.inputBic = new InputTextModule({
		'id' : 'inputBic',
		'label' : I18n.get('bic'),
		'placeholder' : I18n.get('bic'),
		'mandatory' : true,
		'validationPattern' : ValidationPattern.VALID_BIC,
		'onKeyUp' : function() { that.setJQFormTitle(); },
		'onEnter' : function() { that.saveAccount(); }
	});
	this.inputIban = new InputTextModule({
		'id' : 'inputIban',
		'label' : I18n.get('iban'),
		'placeholder' : I18n.get('iban'),
		'mandatory' : true,
		'validationPattern' : ValidationPattern.VALID_IBAN,
		'validationMethod' : new ValidationMethod({
			'errorMessage' : I18n.get('creditor.account.iban.exists'),
			'method' : function(value) {
				var unique = true;
				that.accountTable.objectMap.foreach(function(id, account) {
					unique = unique && (that.account.id == account.id || account.iban != value);
				});
				return unique;
			}
		}),
		'onKeyUp' : function() { that.setJQFormTitle(); },
		'onEnter' : function() { that.saveAccount(); }
	});
}

CreditorAccountModule.neededRoles = ['VIEW_BIC_IBAN'];

CreditorAccountModule.prototype.fillJQ = function(jQ) {
	var that = this;
	
	// Account list title
	jQ.append($('<h5>' + I18n.get('creditor.accounts') + '</h5>'));
	
	// New button
	if (UserManager.hasRoles(['WRITE_BIC_IBAN'])) {
		var buttonNew = $('<div class="btn new">' + I18n.get('new') + ' <i class="icon-plus icon"/></div>');
		buttonNew.click(function() { that.newAccount(); });
		jQ.find('h5:first').append(buttonNew);
	}
	
	// Account list
	jQ.append(this.accountTable.buildJQ());
	
	// Account edition form
	this.jQForm = $('<div id="accountEditionForm"></div>').hide();
	jQ.append(this.jQForm);
	
	// Fills form with selected account
	if (Util.checkObject(this.accountTable.selectedObject)) {
		this.editAccount(this.accountTable.selectedObject.id);
	}
};

/**
 * Fills the JQ representation of the account edition form
 */
CreditorAccountModule.prototype.fillJQForm = function() {
	var that = this;
	
	// Form title
	this.setJQFormTitle();
	
	// Form
	var form = $('<div class="well"></div>');
	this.jQForm.append(form);

	var nameRow = $('<div class="row-fluid"></div>');
	form.append(nameRow);
	var columnLeft = $('<div class="span6"></div>');
	columnLeft.append(this.inputName.buildJQ());
	nameRow.append(columnLeft);

	var bicIbanRow = $('<div class="row-fluid"></div>');
	form.append(bicIbanRow);
	var columnLeft = $('<div class="span6"></div>');
	columnLeft.append(this.inputBic.buildJQ());
	var columnRight = $('<div class="span6"></div>');
	columnRight.append(this.inputIban.buildJQ());
	bicIbanRow.append(columnLeft).append(columnRight);
	
	var buttonRow = $('<div class="btn-row"></div>');
	form.append(buttonRow);
	var buttonSave = $('<div class="btn save">' + I18n.get('save') + '</div>');
	buttonSave.click(function() { that.saveAccount(); });
	buttonRow.append(buttonSave);
};

/**
 * Sets the account edition form title
 */
CreditorAccountModule.prototype.setJQFormTitle = function() {
	var jQFormTitle = this.jQForm.children('h5:first');
	if (!Util.checkJQueryNotEmpty(jQFormTitle)) {
		jQFormTitle = $('<h5></h5>');
		this.jQForm.prepend(jQFormTitle);
	}
	jQFormTitle.clear();
	if (!Util.check(this.account.id)) {
		jQFormTitle.text(I18n.get('creditor.account.new'));
	} else {
		jQFormTitle.text(I18n.get('creditor.account') + ' - ' + this.account.name);
	}
	if (this.isAccountModified()) {
		jQFormTitle.addClass('modified');
		jQFormTitle.append(' *');
	} else {
		jQFormTitle.removeClass('modified');
	}
};

/**
 * Returns true if any modification of in the account edition form is pending
 */
CreditorAccountModule.prototype.isAccountModified = function() {
	return this.inputName.modified || this.inputBic.modified || this.inputIban.modified;
};

/**
 * Loads the creditor and accounts from creditor parameter
 */
CreditorAccountModule.prototype.loadData = function(callback) {
	var that = this;
	
	// Resets the account table object map
	this.accountTable.objectMap = new Map();
	
	// Sets the creditor
	this.creditor = this.parameters.referrer;
	if (!Util.checkObject(this.creditor)) {
		return;
	}
	
	// Fills the account table
	this.creditor.accounts = Util.getObject(this.creditor.accounts);
	$.each(this.creditor.accounts, function(id, account) {
		that.accountTable.objectMap.put(id, account);
	});
	Util.getFunction(callback)();
};

/**
 * Sets the edited account
 */
CreditorAccountModule.prototype.setAccount = function(account) {
	account = Util.getObject(account);
	if (this.account != account) {
		this.account = account;
		
		this.inputName.modified = false;
		this.inputBic.modified = false;
		this.inputIban.modified = false;
		
		this.inputName.setValue(this.account.name);
		this.inputBic.setValue(this.account.bic);
		this.inputIban.setValue(this.account.iban);
	}
	this.validate();
};

/**
 * Edit a new account
 */
CreditorAccountModule.prototype.newAccount = function() {
	this.accountTable.unselect();
	this.setAccount();
	this.jQForm.clear();
	this.fillJQForm();
	this.jQForm.show();
};

/**
 * Edit an account
 */
CreditorAccountModule.prototype.editAccount = function(accountId) {
	this.jQForm.clear();
	if (!Util.check(accountId)) {
		this.jQForm.hide();
		return;
	}
	this.setAccount(this.creditor.accounts[accountId]);
	this.fillJQForm();
	this.jQForm.show();
};

CreditorAccountModule.prototype.setActive = function(account, active) {
	var that = this;
	account.active = active;
	that.saveAccount(account);
};

CreditorAccountModule.prototype.setDefault = function(account) {
	var that = this;
	var oldDefaultAccount = undefined;
	this.accountTable.objectMap.foreach(function(id, acc) {
		if (Util.checkBoolTrue(acc.byDefault)) {
			oldDefaultAccount = acc;
		}
		acc.byDefault = false;
	});
	account.byDefault = true;
	that.saveAccount(account, function() {
		if (Util.checkObject(oldDefaultAccount)) {
			that.saveAccount(oldDefaultAccount);
		}
	});
};

/**
 * Deletes a mandate flow
 */
CreditorAccountModule.prototype.saveAccount = function(account, callback) {
	if(!Util.checkObject(account) && !this.validate()) {
		return;
	}
	
	if (!Util.checkObject(account)) {
		account = Util.getObject(account);
		account.id = this.account.id;
		account.name = this.inputName.value;
		account.bic = this.inputBic.value;
		account.iban = this.inputIban.value;
		account.active = Util.check(this.account.active) ? this.account.active : true;
		account.byDefault = Util.check(this.account.byDefault) ? this.account.byDefault : (!Util.check(this.creditor.accounts) || Object.size(this.creditor.accounts) == 0);
	}
	
	var that = this;
	var selectedObject = this.accountTable.selectedObject;
	AjaxManager.getJSON('saveAccount', {
		'creditorId' : this.creditor.id,
		'account' : JSON.stringify(account)
	}, function(result) {
		if (result.success) {
			that.creditor.accounts = result.accounts;
			that.accountTable.selectedObject = undefined;
			if (Util.checkObject(selectedObject)) {
				$.each(that.creditor.accounts, function(i, creditorAccount) {
					if (creditorAccount.name == selectedObject.name || creditorAccount.iban == selectedObject.iban) {
						that.accountTable.selectedObject = creditorAccount;
					}
				});
			}
			if (Util.checkFunction(callback)) {
				callback();
			} else {
				that.reload();
			}
		}
	});
	return true;
};
